package com.base.netlib.adapter

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException

class BooleanConvertTypeAdapter : TypeAdapter<Boolean?>() {
    @Throws(IOException::class)
    override fun write(out: JsonWriter, value: Boolean?) {
        if (value == null) {
            out.nullValue()
        } else {
            out.value(value)
        }
    }

    @Throws(IOException::class)
    override fun read(readerIn: JsonReader): Boolean? {
        return when (val peek = readerIn.peek()) {
            JsonToken.BOOLEAN -> readerIn.nextBoolean()
            JsonToken.NULL -> {
                readerIn.nextNull()
                null
            }
            JsonToken.NUMBER -> readerIn.nextInt() != 0
            JsonToken.STRING -> {
                val inStr = readerIn.nextString()
                inStr.toBoolean() || "1" == inStr
            }
            else -> throw IllegalStateException("Expected BOOLEAN or NUMBER but was $peek")
        }
    }
}